<?php

require APP_PATH.'/Common/Common/sms.php';
require APP_PATH.'/Common/Common/cache.php';


function importExcel($file, $head = false){
    \Yaf\Loader::import(LIBRARY_PATH . '/PHPExcel.php');
    if (!file_exists($file)) {
        E('exportExcel : File does not exist');
    }

    $objPHPExcel = PHPExcel_IOFactory::load($file);
    $currentSheet = $objPHPExcel->getSheet(0);

    $allColumn = $currentSheet->getHighestColumn(); /* all 列 */
    $allRow = $currentSheet->getHighestRow(); /* all row */

    /* excel all data */
    $sheetAllRow = array();
    for ($currentRow = 1; $currentRow <= $allRow; $currentRow ++) {
        if (is_numeric($head) && $currentRow == $head + 1){
            break;
        }
        $flag = 0;
        $col = array();
        for ($currentColumn = 'A'; ord($currentColumn) <= ord($allColumn); $currentColumn ++) {
            $current = $currentColumn . $currentRow;
            $string = trim((string)$currentSheet->getCell($current)->getValue());
            $col[$flag] = $string;
            $flag ++;
        }
        $sheetAllRow[] = $col;
    }
    return $sheetAllRow;

}

/**
 * 导出数据为excel表格
 *@param $data    一个二维数组,结构如同从数据库查出来的数组
 *@param $title   excel的第一行标题,一个数组,如果为空则没有标题
 *@param $filename 下载的文件名
 *@examlpe exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
 */
function exportExcel($data = array(), $title = array(), $filename = 'report')
{
    header("Content-type:application/octet-stream");
    header("Accept-Ranges:bytes");
    header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:attachment;filename=" . $filename . ".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    if (! empty($title)) {
        foreach ($title as $k => $v) {
            $title[$k] = @iconv("UTF-8", "GBK//IGNORE", $v);
        }
        $title = implode("\t", $title);
        echo "$title\n";
    }
    if (! empty($data)) {
        foreach ($data as $key => $val) {
            foreach ($val as $ck => $cv) {
                $data[$key][$ck] = iconv("UTF-8", "GBK", $cv);
            }
            $data[$key] = implode("\t", $data[$key]);
        }
        echo implode("\n", $data);
    }
}

/**
 * 生成缩略图函数
 * @param  $imgurl 图片路径
 * @param  $width  缩略图宽度
 * @param  $height 缩略图高度
 * @param  $thumb_type 缩微图截取类型
 * @param  $smallpic 无图片是默认图片路径
 */
function thumb($img_url, $width = 100, $height = 100, $thumb_type = 0, $small_pic = null) {
    $img_nopic = empty ( $small_pic ) ? getConfig ( 'image_nopic' ) : $small_pic; // 默认图
    $img_path = str_replace(C("IMG_URL"), PUBLIC_PATH, $img_url);
    if (empty ( $img_url )) return $img_nopic;
    if (! file_exists ( $img_path )) return $img_nopic;
    list ( $width_t, $height_t, $type, $attr ) = getimagesize ( $img_path );
    //if ($width >= $width_t || $height >= $height_t) return $img_url;
    //$width = $width_t;
    $img_name = basename ( $img_url );
    $img_path = str_replace ( $img_name, '', $img_path );
    $new_img_path = $img_path . 'thumb_' . $width . '_' . $height . '_' . $thumb_type . '_' . $img_name;
    $thumb_url = ltrim ( $new_img_path, '.' );
    if (file_exists ( $new_img_path )) return str_replace(PUBLIC_PATH, C("IMG_URL"), $thumb_url);
    switch ($thumb_type) {
        case 1 : // 缩略图等比例缩放类型
            $Image = new \Think\Image ();
            $Image->open ( $img_path . $img_name );
            $thumb = $Image->thumb ( $width, $height, \Think\Image::IMAGE_THUMB_SCALE )->save ( $new_img_path );
            break;
        case 2 : // 缩略图缩放后填充类型
            $Image = new \Think\Image ();
            $Image->open ( $img_path . $img_name );
            $thumb = $Image->thumb ( $width, $height, \Think\Image::IMAGE_THUMB_FILLED )->save ( $new_img_path );
            break;
        case 3 : // 缩略图居中裁剪类型
            $Image = new \Think\Image ();
            $Image->open ( $img_path . $img_name );
            $thumb = $Image->thumb ( $width, $height, \Think\Image::IMAGE_THUMB_CENTER )->save ( $new_img_path );
            break;
        case 4 : // 缩略图左上角裁剪类型
            $Image = new \Think\Image ();
            $Image->open ( $img_path . $img_name );
            $thumb = $Image->thumb ( $width, $height, \Think\Image::IMAGE_THUMB_NORTHWEST )->save ( $new_img_path );
            break;
        case 5 : // 缩略图右下角裁剪类型
            $Image = new \Think\Image ();
            $Image->open ( $img_path . $img_name );
            $thumb = $Image->thumb ( $width, $height, \Think\Image::IMAGE_THUMB_SOUTHEAST )->save ( $new_img_path );
            break;
        case 6 : // 缩略图固定尺寸缩放类型
            $Image = new \Think\Image ();
            $Image->open ( $img_path . $img_name );
            $thumb = $Image->thumb ( $width, $height, \Think\Image::IMAGE_THUMB_FIXED )->save ( $new_img_path );
            break;
        default :
            $Image = new \Think\Image ();
            $Image->open ( $img_path . $img_name );
            $thumb = $Image->thumb ( $width, $height, \Think\Image::IMAGE_THUMB_SCALE )->save ( $new_img_path );
            break;
    }
    return is_object($thumb) ? str_replace(PUBLIC_PATH, C("IMG_URL"), $thumb_url) : $img_url;
}


/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * @return string
 */
function encrypt($data, $key = '', $expire = 0) {
    $key  = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time():0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串
 * @param  string $key  加密密钥
 * @return string
 */
function decrypt($data, $key = ''){
    $key    = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);

    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

/**
 * 发送HTTP请求方法，目前只支持CURL发送请求
 * @param  string $url    请求URL
 * @param  array  $params 请求参数
 * @param  string $method 请求方法GET/POST
 * @return array  $data   响应数据
 */
function curlHttp($url, $params, $method = 'GET', $header = array(), $multi = false)
{
    $opts = array(
        CURLOPT_TIMEOUT => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => $header
    );
    
    /* 根据请求类型设置特定参数 */
    switch (strtoupper($method)) {
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            // 判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式！');
    }
    
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    // $head = curl_getinfo($ch,CURLINFO_CONTENT_TYPE);
    curl_close($ch);
    if ($error){
        throw new Exception('请求发生错误：' . $error);
    }    
    return $data;
}


/**
 * 格式化时间
 */
function time_format($time = NULL,$format='Y-m-d H:i'){
    if ($time == 0 || $time == '') {
        return '无';
    }
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}



/**
 * 返回配置的值
 *
 * @param String $key 	名称
 * @return String 值
 */
function getConfig($key, $cache = true)
{
    $cacheKey = C('CACHE_KEY_CONFIG') . $key;
    $cacheData = S($cacheKey);
    if (empty($cacheData) || ! $cache) {
        $setting = M('Setting');
        $map['set_key'] = $key;
        $result = $setting->where($map)->find();
        if (false === $result) {
            return false;
        } else {
            S($cacheKey, $result['set_value']);
            return $result['set_value'];
        }
    } else {
        return $cacheData;
    }
}

/**
 * 保存配置值到数据库
 *
 * @param string $key            
 * @param string $value            
 * @return boolean
 */
function setConfig($key, $value = null)
{
    if (is_null($value)) {
        return false;
    } else {
        $setting = M('Setting');
        $map['set_key'] = $key;
        $date['set_value'] = $value;
        $info = $setting->where($map)->find();
        if ($info) {
            $setting->where($map)->save($date);
        } else {
            $data['set_key'] = $key;
            $setting->add($data);
        }
        return true;
    }
}

/**
 * @验证手机号是否正确
 * 
 * @param string $mobile            
 * @return bool
 */
function isValidMobile($mobile)
{
    return preg_match("/^1[34578]\d{9}$/", trim($mobile));
}

/**
 * @获取二维码
 * 
 * @param int $memberID 会员ID
 * @param string $content 二维码内容
 * @param string $outfile 文件地址及文件名
 * @param string $level
 * @param int $size
 * @param int $margin
 * @return path
 */
function getQrcode($content = '', $outfile = '', $level = 'L', $size = 8, $margin = 2)
{
    if (empty($outfile)) {
        $file_name = md5(time() . rand(1, 99999));
        $qrcode_dir = C('QRCODE_PATH') . date("Ymd") . '/';
        if (! is_dir($qrcode_dir)) {
            mkdir($qrcode_dir, 0755, true);
        }
        $outfile = $qrcode_dir . $file_name . '.png';
    } else {
        $file_arr = pathinfo($outfile);
        $qrcode_dir = $file_arr['dirname'];
        $file_name = $file_arr['filename'];
        if (! is_dir($qrcode_dir)) {
            mkdir($qrcode_dir, 0755, true);
        }
    }
    vendor('phpqrcode.phpqrcode');
    QRcode::png($content, $outfile, $level, $size, $margin);
    if (file_exists($outfile)) {
        $outfile = str_replace(PUBLIC_PATH, C('IMG_URL'), $outfile);
        return $outfile;
    } else {
        return false;
    }
}


/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}


/**
 * 生成唯一couponsn
 * @return  string
 */
function getCouponSN()
{
    // php系统函数 10位时间戳 小数点 4位毫秒数
    $numA = microtime(true) * 10000;
    // 去掉最后1位，保留3位毫秒数
    $numB = substr($numA, 0, -1);
    // 随机5位数 1-99999 不足5位数 前面补0
    $rand = str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    // 最后生成18位 整数 列如：14515337733786325
    return $numB . $rand;
}


/**
 * 生成唯一订单号
 * @return  string
 */
function getOrderSN()
{
    // php系统函数 10位时间戳 小数点 4位毫秒数
    $numA = microtime(true) * 10000;
    // 去掉最后1位，保留3位毫秒数
    $numB = substr($numA, 0, -1);
    // 随机5位数 1-99999 不足5位数 前面补0
    $rand = str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    // 最后生成18位 整数 列如：14515337733786325
    return $numB . $rand;
}


/**
 * 为某商品生成唯一的货号
 */
function getGoodsSN($maxID = '')
{
    $maxID = ! empty($maxID) ? $maxID : (D('Goods')->getMaxID() + 1);
    $goodsSN = 'BT' . str_repeat('0', 8 - strlen($maxID)) . $maxID;
    $bool = M('Goods')->where(array( 'goods_sn' => $goodsSN ))->count();
    if (! empty($bool)) {
        $goodsSN = getGoodsSN(($maxID + 1));
    }
    return $goodsSN;
}

/**
 * 获取会员卡号
 */
function getVipSN($memberID)
{
    $vipSN = '1' . str_repeat('0', 15 - strlen($memberID)) . $memberID;
    return $vipSN;
}

/**
 * 关注和取消关注日志
 * @param array $data 响应的数据
 * @return bool
 */
function addWechatSubscribeLog($data)
{
    return M('WechatSubscribe')->add(array(
        'openid' => $data['FromUserName'],
        'msg_type' => $data['Event'],
        'content' => json_encode($data),
        'create_time' => $data['CreateTime']
    ));
}

/**
 * 发优惠券
 * @param $memberID
 * @param $couponID
 * @param int $sendType
 * @return bool|mixed
 */
function addMemberCoupon($memberID, $couponID, $sendType = 0)
{
    if (empty($memberID) || empty($couponID)){
        return false;
    }
    $coupon = getCouponList();
    if (empty($coupon[$couponID])){
        return false;
    }
    $data = array();
    $data['member_id'] = $memberID;
    $data['coupon_id'] = $couponID;
    $data['coupon_sn'] = getCouponSN();
    $data['coupon_name'] = $coupon[$couponID]['coupon_name'];
    $data['coupon_value'] = $coupon[$couponID]['coupon_value'];
    $data['start_time'] = $coupon[$couponID]['start_time'];
    $data['end_time'] = $coupon[$couponID]['end_time'];
    $data['min_amount'] = $coupon[$couponID]['min_amount'];
    $data['send_type'] = $sendType;
    $data['status'] = 1;
    $data['use_time'] = 0;
    $data['create_time'] = time();
    return M('MemberCoupon')->add($data);
}

/**
 * @param $data
 * @param int $operatorID
 * @param string $operator
 * @return mixed
 */
function addCouponLog($data, $operatorID = 0, $operator = '')
{
    $log = array();
    $log['member_id'] = $data['member_id'];
    $log['coupon_id'] =  $data['coupon_id'];
    $log['coupon_sn'] = $data['coupon_sn'];
    $log['coupon_name'] = $data['coupon_name'];
    $log['coupon_value'] = $data['coupon_value'];
    $log['operator_id'] = $operatorID;
    $log['operator'] = $operator;
    $log['logtime'] = time();
    return M('CouponLog')->add($log);
}

function getNowMenu($regionID)
{
    $area = M('AreaRegion')->where(array('region_id' => $regionID))->find();
    if (empty($area)) {
        return false;
    }
    $time = time();
    $where = array();
    $where['status'] = 1;
    $where['area_id'] = $area['area_id'];
    $where['start_sell_time'] = array('elt', $time);
    $where['end_sell_time'] = array('egt', $time);
    return M('AreaGoods')->where($where)->order('id DESC')->find();
}



function getOptimalCoupon($memberID)
{
    $time = time();
    $where = array();
    $where['status'] = 1;
    $where['member_id'] = $memberID;
    $where['start_time'] = array('lt', $time);
    $where['end_time'] = array('gt', $time);
    return M('MemberCoupon')->where($where)->order('coupon_value DESC')->find();
}

/**
 * 订单状态
 * 订单状态：0:已取消 1:未付款 2:已付款 3:已发货 4:已收货
 */
function getOrderState($state = 0)
{
    switch ($state) {
        case 0:
            $str = "已取消";
            break;
        case 1:
            $str = "未付款";
            break;
        case 2:
            $str = "已付款";
            break;
        case 3:
            $str = "已发货";
            break;
        case 4:
            $str = "已收货";
            break;
        default:
            $str = "已取消";
            break;
    }
    return $str;
}


/**
 * 订单状态
菜单的响应动作类型----目前建议直选click或者view<br />
1、click：点击推事件用户点击click类型按钮后，微信服务器会通过消息接口推送消息类型为event的结构给开发者（参考消息接口指南），并且带上按钮中开发者填写的key值，开发者可以通过自定义的key值与用户进行交互；<br />
2、view：跳转URL用户点击view类型按钮后，微信客户端将会打开开发者在按钮中填写的网页URL，可与网页授权获取用户基本信息接口结合，获得用户基本信息。<br />
3、scancode_push：扫码推事件用户点击按钮后，微信客户端将调起扫一扫工具，完成扫码操作后显示扫描结果（如果是URL，将进入URL），且会将扫码的结果传给开发者，开发者可以下发消息。<br />
4、scancode_waitmsg：扫码推事件且弹出“消息接收中”提示框用户点击按钮后，微信客户端将调起扫一扫工具，完成扫码操作后，将扫码的结果传给开发者，同时收起扫一扫工具，然后弹出“消息接收中”提示框，随后可能会收到开发者下发的消息。<br />
5、pic_sysphoto：弹出系统拍照发图用户点击按钮后，微信客户端将调起系统相机，完成拍照操作后，会将拍摄的相片发送给开发者，并推送事件给开发者，同时收起系统相机，随后可能会收到开发者下发的消息。<br />
6、pic_photo_or_album：弹出拍照或者相册发图用户点击按钮后，微信客户端将弹出选择器供用户选择“拍照”或者“从手机相册选择”。用户选择后即走其他两种流程。<br />
7、pic_weixin：弹出微信相册发图器用户点击按钮后，微信客户端将调起微信相册，完成选择操作后，将选择的相片发送给开发者的服务器，并推送事件给开发者，同时收起相册，随后可能会收到开发者下发的消息。<br />
8、location_select：弹出地理位置选择器用户点击按钮后，微信客户端将调起地理位置选择工具，完成选择操作后，将选择的地理位置发送给开发者的服务器，同时收起位置选择工具，随后可能会收到开发者下发的消息。<br />
9、media_id：下发消息（除文本消息）用户点击media_id类型按钮后，微信服务器会将开发者填写的永久素材id对应的素材下发给用户，永久素材类型可以是图片、音频、视频、图文消息。请注意：永久素材id必须是在“素材管理/新增永久素材”接口上传后获得的合法id。<br />
10、view_limited：跳转图文消息URL用户点击view_limited类型按钮后，微信客户端将打开开发者在按钮中填写的永久素材id对应的图文消息URL，永久素材类型只支持图文消息。请注意：永久素材id必须是在“素材管理/新增永久素材”接口上传后获得的合法id<br />
 */
function getMenuType($menuType = 0)
{
    switch ($menuType) {
        case 1:
            $str = "click";
            break;
        case 2:
            $str = "view";
            break;
        case 3:
            $str = "scancode_push";
            break;
        case 4:
            $str = "scancode_waitmsg";
            break;
        case 5:
            $str = "pic_sysphoto";
            break;
        case 6:
            $str = "pic_photo_or_album";
            break;
        case 7:
            $str = "pic_weixin";
            break;
        case 8:
            $str = "location_select";
            break;
        case 9:
            $str = "media_id";
            break;
        case 10:
            $str = "view_limited";
            break;
        default:
            $str = "view";
            break;
    }
    return $str;
}


function getWeek($time)
{
    return '周' . mb_substr("日一二三四五六", date('w', $time), 1, 'utf-8');
}

function getNextWeek($week)
{
    switch ($week) {
        case '周一':
            $str = "周二";
            break;
        case '周二':
            $str = "周三";
            break;
        case '周三':
            $str = "周四";
            break;
        case '周四':
            $str = "周五";
            break;
        case '周五':
            $str = "周一";
            break;
        case '周六':
            $str = "周一";
            break;
        case '周日':
            $str = "周一";
            break;
    }
    return $str;
}

function getTodayMenu($regionID, $menuDate)
{
    $area = M('AreaRegion')->where(array('region_id' => $regionID))->find();
    if (empty($area)) {
        return false;
    }
    $where = array();
    $where['status'] = 1;
    $where['area_id'] = $area['area_id'];
    $where['menu_date'] = $menuDate;
    return M('Menu')->where($where)->order('menu_id DESC')->find();
}

function getTodayMenus($regionID, $menuDate)
{
    $area = M('AreaRegion')->where(array('region_id' => $regionID))->find();
    if (empty($area)) {
        return false;
    }
    $where = array();
    $where['status'] = 1;
    $where['area_id'] = $area['area_id'];
    $where['menu_date'] = array('in', $menuDate);
    return M('Menu')->where($where)->getField('menu_date,id,menu_date,area_id,start_sell_time,end_sell_time,start_deliver_time,end_deliver_time');
}


function getIds($list = array(), $field = 'id')
{
    if (! is_array($list)) {
        return false;
    }
    $ids = array();
    foreach ($list as $key => $val) {
        $ids[] = $val[$field];
    }
    return $ids;
}

function getMenuDate_old()
{
    $time = time();
    $menuDate = array();
    for ($i = 0; $i <= 4; $i++) {
        if ($i == 0) {
            $menuDate[] = strtotime(date('Y-m-d 00:00:00', $time));
        } else {
            $tTime = strtotime("+{$i} day", $time);
            $menuDate[] = strtotime(date('Y-m-d 00:00:00', $tTime));
        }
    }
    return $menuDate;
}

function getMenuDate($regionID)
{
    $menuDate = strtotime(date('Y-m-d'));

    $area = M('AreaRegion')->where(array('region_id' => $regionID))->find();
    if (empty($area)) {
        return false;
    }
    $where = array();
    $where['status'] = 1;
    $where['area_id'] = $area['area_id'];
    $where['menu_date'] = ['egt', $menuDate];
    $result = M('Menu')->field('menu_id,menu_date,area_id')->where($where)->order('menu_id ASC')->limit(5)->select();
    return $result;

}



function getStorageActivity($menuGoods){
    $key = C('CACHE_KEY_MENU_GOODS_SELL_NUM') . $menuGoods['menu_id'] . '_' .  $menuGoods['goods_id'];
    $sellNum = S($key);

    $surplus = $menuGoods['goods_storage'] - $sellNum;
    $surplus = $surplus <= 0 ? 0 : $surplus;

    $result = array('sub' => 0, 'discount' => 0);
    if (getConfig('storage_activity')){
        if ($surplus > 0){
            $sub = 100 - (round($surplus/$menuGoods['goods_storage']) * 100);
            $result['sub'] = $sub <= 0 ? 0 : $sub;
            if ($surplus <= $menuGoods['storage_one']){
                $result['discount'] = $menuGoods['sale_one'];
            } elseif($surplus > $menuGoods['storage_one'] && $surplus <= $menuGoods['storage_two']){
                $result['discount'] = $menuGoods['sale_two'];
            } elseif($surplus > $menuGoods['storage_two']){
                $result['discount'] = $menuGoods['sale_three'];
            } else {
                $result['sub'] = 100;
                $result['discount'] = 0;
            }
        } else {
            $result['sub'] = 100;
            $result['discount'] = 0;
        }
    }
    return $result;
}